package com.android_map_app.activities;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.android_map_app.R;
import com.android_map_app.data.ResultType;

public class GroupListActivity extends ListActivity {
	 
	public final int MAKE_GROUP = Menu.FIRST;
	public final int MAKE_ACTIVE = Menu.FIRST;
	public final int DIALOG_ID = 7;
	private String[] mGroups;
	private SharedPreferences mPrefs;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.groups_list);
		mPrefs = getSharedPreferences(MainActivity.USER_PREF, MODE_PRIVATE);
		new fillGroups().execute();
		registerForContextMenu(getListView());
	}
		
	@Override
	public void onRestart() {
		super.onRestart();
		new fillGroups().execute();
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, MAKE_GROUP, 0, R.string.make_group);
        return result;
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MAKE_GROUP:
            startActivity(new Intent(getApplicationContext(), MakeGroupActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent(getApplicationContext(), GroupActivity.class);
		intent.putExtra("groupName", mGroups[position]);
		startActivity(intent);

	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
	        ContextMenu.ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);
	    menu.add(0, MAKE_ACTIVE, 0, R.string.make_group_active_short);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    switch(item.getItemId()) {
	    case MAKE_ACTIVE:
	        new makeGroupActive().execute(mGroups[(int) info.id]);
	        return true;
	    }
	    return super.onContextItemSelected(item);
	}

	private String[] getGroups() {
		try {
			URL url = new URL("http://" + getBaseContext().getString(R.string.server_name)
					+ "/update?action=getAllGroups");
			BufferedReader br = new BufferedReader(
					new InputStreamReader(url.openStream()));
			JSONArray groups = (new JSONObject(br.readLine())).getJSONArray("groups");
			br.close();
			String[] result = new String[groups.length()];
			for (int i = 0; i < groups.length(); i++) result[i] = groups.get(i).toString();
			return result;
		} catch (Throwable e) {
			displayToast("Connection error");
			return null;
		}	
	}
	
	private void displayToast(String message) {
		Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL, 0, 0);
		toast.show();
	}
	
	private class fillGroups extends AsyncTask<String, Integer, ResultType> {
		@Override
		protected ResultType doInBackground(String... params) {
			mGroups = getGroups();
			if (mGroups != null) return ResultType.SUCCESS;
			else {
				return ResultType.ERROR;
			}
		}

		@Override
		protected void onPostExecute(ResultType result) {
			super.onPostExecute(result);
			switch (result) {
			case SUCCESS:
				setListAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.grouplist_item, mGroups));
				break;
			case ERROR:
				displayToast("Connection error.");
				break;
			}
		}
	}
	
	private class makeGroupActive extends AsyncTask<String, Integer, ResultType> {
		@Override
		protected ResultType doInBackground(String... params) {
			try {
				URL url = new URL("http://" + getBaseContext().getString(R.string.server_name)
						+ "/update?action=validateMakeActive"
						+ "&idCode=" + mPrefs.getString("idCode", "")
						+ "&groupName=" + params[0]);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(url.openStream()));
				String result = br.readLine();
				br.close();
				if (!result.equals("FAIL")) {
					SharedPreferences.Editor editor = mPrefs.edit();
					editor.putString("activeGroup", params[0]);
					editor.commit();
					return ResultType.SUCCESS;
				}
				else {
					return ResultType.ERROR;
				}
			} catch (Throwable e) {
				displayToast("Connection error");
				return ResultType.ERROR;
			}
		}

		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_ID);
		}
		@Override
		protected void onPostExecute(ResultType result) {
			super.onPostExecute(result);
			dismissDialog(DIALOG_ID);
			switch (result) {
			case SUCCESS:
				displayToast("The group is now active");
				break;
			case ERROR:
				displayToast("You haven't joined this group!");
				break;
			}
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ID:
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage(GroupListActivity.this.getString(R.string.stringDataWait));
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		return null;
	}
}
